Reading from a TextArea
Below is code that reads one line from a textarea. The key things are:
- the keys that i did was add a keylistener to textarea
- look at testinteraction - it calls a method (readLine - copy that),
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class FullScreen extends JApplet implements ActionListener, KeyListener
{
JTextArea textArea;
JButton closeButton = new JButton("X");
String lastNewLine="";
public void init()
{
Container screen = getContentPane();
screen.setBackground(Color.green);
screen.setLayout (new FlowLayout());
screen.add(closeButton);
textArea = new JTextArea(5, 30);
textArea.addKeyListener(this);
screen.add(textArea);
}
public void paint(Graphics g)
{
super.paint(g);
}
public void testInteraction()
{
textArea.append("whats your name?\n");
setCursorEnd();
}
public void processLine()
{
textArea.append("nice to meet you\n" +lastNewLine);
setCursorEnd();
lastNewLine="";
}
public void setCursorEnd()
{
textArea.setCaretPosition(textArea.getDocument().getLength());
}
public String readLine()
{
Document document = textArea.getDocument();
Element rootElem = document.getDefaultRootElement();
int numLines = rootElem.getElementCount();
Element lineElem = rootElem.getElement(numLines - 1);
int lineStart = lineElem.getStartOffset();
int lineEnd = lineElem.getEndOffset();
try{
String lineText = document.getText(lineStart, lineEnd - lineStart);
lineText=lineText.replace("\n","");
return lineText;
}
catch (Exception e){}
return "";
// return textArea.getText();
}
public void actionPerformed(ActionEvent thisEvent)
{
Object source = thisEvent.getSource();
if (source == closeButton)
{
System.exit(0);
}
}
int gameStatus=0;
public void keyPressed(KeyEvent e)
{
char theChar=e.getKeyChar();
int theCode=e.getKeyCode();
if (theCode == e.VK_ENTER) {
lastNewLine=readLine();
processLine();
}
}
//This is the method that will be called if a key is released
//It is unneccessary to use this method, but you must include it
public void keyReleased(KeyEvent e)
{
}
//This is the method that will be called if a key is typed, however you cant use getKeyCode, so
// you are better to use keyPressed
public void keyTyped(KeyEvent e)
{
}
}
|